package cn.xzqwjw.taskmanager.utils;

import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HTTP 输出响应内容工具类
 *
 * @author rush
 */
@Slf4j
public class ResponseUtil {

  // 下面三个 write() 方法参数是不一样的，
  // 一个是 String 类型的 message，
  // 一个是 Object 类型的 message，
  // 一个是 File 类型

  /**
   * 发送HTTP响应信息
   *
   * @param response HttpServletResponse响应对象
   * @param message  String类型信息内容
   */
  public static void writeHtmlPage(HttpServletResponse response, String message) {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter writer = response.getWriter()) {
      writer.write(message);
      writer.flush();
    } catch (IOException e) {
      log.error("writeHtmlPage() 发生错误：{}", e.getMessage());
    }
  }

  /**
   * 发送HTTP响应信息,不带JWT的JSON格式
   *
   * @param response   HTTP响应对象
   * @param responseVo 输出对象
   */
  public static void writeJson(HttpServletResponse response, ResponseVo responseVo) {
    // setHttpResponse(response);
    response.setContentType("application/json;charset=UTF-8");
    try (PrintWriter writer = response.getWriter()) {
      writer.write(JsonUtil.obj2Json(responseVo));
      writer.flush();
    } catch (IOException e) {
      log.error("writeJson() 发生错误：{}", e.getMessage());
    }
  }

  /**
   * 发送HTTP响应信息,带JWT的JSON格式
   *
   * @param response   HTTP响应对象
   * @param strJwt     格式化好的JWT字符串
   * @param responseVo 输出对象
   */
  public static void writeJsonJwt(HttpServletResponse response, String strJwt, ResponseVo responseVo) {
    // setHttpResponse(response);
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("authorization", strJwt);
    try (PrintWriter writer = response.getWriter()) {
      writer.write(JsonUtil.obj2Json(responseVo));
      writer.flush();
    } catch (IOException e) {
      log.error("writeJsonJwt() 发生错误：{}", e.getMessage());
    }
  }

  public static String writePageData(Page<?> page, List<?> listData, Integer pageSize) {
    // 只有经过上面的获取分页数据操作才能得到下面的记录总数和总页数
    long recordCount = page.getTotal();
    int pageCount = CommonUtil.getPageCount(recordCount, pageSize);
    Map<String, Object> map = new HashMap<>(16);
    map.put("RecordCount", recordCount);
    map.put("PageCount", pageCount);
    map.put("ListData", listData);
    return JsonUtil.obj2Json(ResponseVo.success(map));
  }

}
